package com.example.pt.service;

import com.example.pt.entity.Invitation;
import com.example.pt.repository.InvitationRepositories;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 邀请码服务
 */
@Service
public class InvitationService {
    private InvitationRepositories invitationRepositories;

    public InvitationService(InvitationRepositories invitationRepositories) {
        this.invitationRepositories = invitationRepositories;
    }

    /**
     * 根据邀请码查询邀请记录
     * @param invitationCode 邀请码
     * @return 是否存在有效邀请码
     */
    public boolean searchByInvitation_code(String invitationCode){
        Invitation invitation = invitationRepositories.findByInvitationCode(invitationCode);
        return invitation != null && invitation.isValid();
    }
    
    /**
     * 获取用户的所有邀请码
     * @param userId 用户ID
     * @return 邀请码列表
     */
    public List<Invitation> getUserInvitations(Integer userId) {
        // 从所有邀请码中筛选出该用户的邀请码
        return invitationRepositories.findAll().stream()
                .filter(invitation -> invitation.getUid().equals(userId))
                .toList();
    }
    
    /**
     * 检查邀请码是否有效
     * @param invitationCode 邀请码
     * @return 是否有效
     */
    public boolean isInvitationValid(String invitationCode) {
        Invitation invitation = invitationRepositories.findByInvitationCode(invitationCode);
        return invitation != null && invitation.isValid();
    }
    
    /**
     * 获取邀请码
     * @param invitationCode 邀请码
     * @return 邀请码对象，如果不存在返回null
     */
    public Invitation getInvitation(String invitationCode) {
        return invitationRepositories.findByInvitationCode(invitationCode);
    }
    
    /**
     * 获取邀请码当前已使用次数
     * @param invitationCode 邀请码
     * @return 已使用次数，如果邀请码不存在返回-1
     */
    public int getInvitationUsedCount(String invitationCode) {
        Invitation invitation = invitationRepositories.findByInvitationCode(invitationCode);
        if (invitation == null) {
            return -1;
        }
        return invitation.getInvitationNumber() == null ? 0 : invitation.getInvitationNumber();
    }
}
